#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
#include <unistd.h>
#include "Log.hpp"
using namespace std;
// std::string serverip = "212.64.14.243";
// uint16_t serverport = 8888;
Log lg;

void Usage(const std::string &cmd)
{
    cout << "\n\r" << cmd << " serverip serverport" << endl
         << endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }

    string ip = argv[1];
    uint16_t port = stoi(argv[2]);
    while (true)
    {
        char buffer[4096];
        int cnt = 5;
        bool isrconnect = false;
        int sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (sockfd < 0)
        {
            lg(Fatal, "create socket error, sockfd: %d", sockfd);
            return 2;
        }
        lg(Info, "create socket success, sockfd: %d", sockfd);

        struct sockaddr_in server;
        socklen_t len = sizeof(server);
        memset(&server, 0, len);
        server.sin_family = AF_INET;
        server.sin_addr.s_addr = inet_addr(ip.c_str()); // 1.string->int 2.htonl
        server.sin_port = htons(port);

        //断线重连
        do
        {
            if(connect(sockfd, (sockaddr *)&server, len) < 0)
            {
                isrconnect = true;
                sleep(2);
                cerr << "connect err, reconnect: " << cnt-- << endl; 
            }
            else
            {
                cout << "connect success" << endl;
                break;
            }
        } while (cnt && isrconnect);
        if(cnt == 0)
        {
            cerr << "user offline..." << endl;
            return 2;
        }

        string message;
        cout << "please Enter# ";
        getline(cin, message);
        int n = write(sockfd, message.c_str(), message.size());
        if(n < 0)
        {
            cerr << "write err: " << errno << " errstring: " << strerror(errno) << endl;
            continue;
        }

        n = read(sockfd, buffer, sizeof(buffer) - 1);
        if(n > 0)
        {
            buffer[n] = 0;
            cout << buffer << endl;
        }
        else
        {

        }
        close(sockfd);
    }

    return 0;
}